package org.javaboy.vhr.service;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.formula.functions.T;
import org.javaboy.vhr.mapper.HrMapper;
import org.javaboy.vhr.mapper.OrderMapper;
import org.javaboy.vhr.model.*;
import org.javaboy.vhr.utils.DateUtils;
import org.javaboy.vhr.utils.HrUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderService {
    @Autowired
    private OrderMapper ordermapper;
   @Autowired
   private HrMapper hrMapper;


    public Orders getById(int id) {
        System.out.println(id+"123");
        Orders order =  ordermapper.selectByPrimaryKey(id);
        return order;
    }
    public int complete(int id) throws ParseException {
        int result = 0;
        Orders order = ordermapper.selectByPrimaryKey(id);
        if(!order.getSumTime().equals("未处理")){
            return 5;
        }
        String sumTime = "";
        Integer currentHrId = HrUtils.getCurrentHr().getId();
        String format = "yyyy-MM-dd HH:mm:ss";
        // 按照传入的格式生成一个simpledateformate对象
        SimpleDateFormat sd = new SimpleDateFormat(format);
        if(currentHrId.equals(order.getHrId())){
            Date currentDate = new Date();
            order.setFinishAt(currentDate);
           String startTime = DateUtils.getStringDate(order.getCreatedAt());
           String endTime = DateUtils.getStringDate(currentDate);
           Long diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
           Long d = DateUtils.dateDiff(startTime,endTime,"d");
           Long h = DateUtils.dateDiff(startTime,endTime,"h");
           Long m = DateUtils.dateDiff(startTime,endTime,"m");
           if(d!=0){
               sumTime = d+"天"+h+"小时"+m+"分";
           }else{
               if(h==0){
                   sumTime = m+"分";
               }else{
                   sumTime=h+"小时"+m+"分";
               }
           }
           order.setSumTime(sumTime);
           order.setDiff(diff);
           result =  ordermapper.updateByPrimaryKeySelective(order);
        }else{
            result = 2;
        }
        return result;
    }
    public List<Orders> getList(Integer page,Integer size){
        // newProxyInstance的三个参数解释：
        // 参数1：代理类的类加载器，同目标类的类加载器
        // 参数2：代理类要实现的接口列表，同目标类实现的接口列表
        // 参数3：回调，是一个InvocationHandler接口的实现对象，当调用代理对象的方法时，执行的是回调中的invoke方法
        //proxy为代理对象


        OrderMapper orderMapper = (OrderMapper) Proxy.newProxyInstance(ordermapper.getClass().getClassLoader(), ordermapper.getClass().getInterfaces(), new InvocationHandler() {
            //必须重写invoke方法
            // 参数proxy:被代理的对象,这个对象就是ordermapper
            // 参数method:执行的方法，代理对象执行哪个方法，method就是哪个方法，比如下边的getList
            // 参数args:执行方法的参数:这里没有

            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                System.out.println("生活真的艰难");
                System.out.println(objects);
                System.out.println(method.toString());
                Object result = method.invoke(ordermapper, objects);
                return result;
            }
        });
        List<Orders> ordersList = orderMapper.getList();
        System.out.println(ordersList);
        return ordersList;
    }

    public RespPageBean getEmployeeByPage(Integer page,Integer size){
        System.out.println(page+size+"23424");
        PageHelper.startPage(page,size);
        List<Orders> ordersList = ordermapper.getList();
        System.out.println(ordersList);
        /*PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);*/
        ordersList.stream().forEach(p->p.setUserface(hrMapper.selectByPrimaryKey(p.getHrId()).getUserface()));
        RespPageBean respPageBean = new RespPageBean();

        respPageBean.setData(ordersList);
        Long total =   ordermapper.getCount();
        respPageBean.setTotal(total);
        return respPageBean ;

    }
    public RespPageBean search(Integer page,Integer size ,String keyword){

        PageHelper.startPage(page,size);
        List<Orders> ordersList = ordermapper.searchList(keyword);
        System.out.println(ordersList);
        /*PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);*/

        RespPageBean respPageBean = new RespPageBean();
        respPageBean.setData(ordersList);
        int total =  ordersList.size();

        respPageBean.setTotal(Long.parseLong(total+""));
        return respPageBean ;

    }
    public Integer delete( Integer id){
        Integer currentHrId = HrUtils.getCurrentHr().getId();
        if(currentHrId != 3){
            return 2;
        }
        return ordermapper.deleteByPrimaryKey(id);
    }


    public Integer save(Orders orders) {
        orders.setCreatedAt(new Date());
        orders.setUpdatedAt(new Date());
        Hr hr = hrMapper.selectByPrimaryKey(orders.getHrId());
        orders.setHrName(hr.getName());
        Category category =  ordermapper.getCategoryById(orders.getCategoryId());
        orders.setCategory(category.getCategory());
        orders.setSumTime("未处理");
          int result = ordermapper.insertSelective(orders);
        return result;
    }
    public Integer update(Orders orders) {
        if(!orders.getSumTime().equals("未处理")){
            return 5;
        }
        orders.setUpdatedAt(new Date());
        Hr hr = hrMapper.selectByPrimaryKey(orders.getHrId());
        orders.setHrName(hr.getName());
        Category category =  ordermapper.getCategoryById(orders.getCategoryId());
        orders.setCategory(category.getCategory());
        int result = ordermapper.updateByPrimaryKeySelective(orders);
        return result;
    }
    public List<PersonResult> getPersonInfo(Times times) {
        List<PersonResult> personResultList = new ArrayList<>();
        List<Hr> hrList = hrMapper.getHrs();
        List<Orders> allOrders =  ordermapper.getTimes(times);
        if(allOrders.size()<=0){
            return personResultList;

        }        for (Hr hr:hrList) {
            PersonResult personResult =new PersonResult();
            List<Orders> ordersList = allOrders.stream().filter(p->p.getHrId()==hr.getId()).collect(Collectors.toList());
            if(ordersList.size()<=0){
                continue;

            }
            personResult.setHrName(hr.getName());
            personResult.setSumCount(ordersList.size());
            int unCount = (int) ordersList.stream().filter(p->p.getSumTime().equals("未处理")).count();
            personResult.setUnCount(unCount);
            personResult.setComCount(ordersList.size()-unCount);
            List<Orders> orders = ordersList.stream().filter(p->!p.getSumTime().equals("未处理")).collect(Collectors.toList());
            if(orders.size() > 0){
                OptionalDouble avgTime = orders.stream().mapToLong(Orders::getDiff).average();
                personResult.setAvgTime(getAvg((long) avgTime.getAsDouble()));
            }

            personResultList.add(personResult);
        }
        return personResultList;
    }


    public TimesRes getTimes(Times times) {
        TimesRes timesRes = new TimesRes();
        List<Orders> ordersList = ordermapper.getTimes(times);
        if(ordersList.size()<=0){
            return timesRes;
        }
        timesRes.setSumCount(ordersList.size());
        int unCount = (int) ordersList.stream().filter(p->p.getSumTime().equals("未处理")).count();
        timesRes.setUnCount(unCount);
        timesRes.setComCount(ordersList.size()-unCount);
        List<Type> typeList = new ArrayList<>();
        List<Category> categories = ordermapper.getCategoryList();
        OptionalDouble avgxtime = ordersList.stream().mapToLong(Orders::getXtime).average();
        timesRes.setAvgxtime(String.format("%.2f", avgxtime.getAsDouble())+"分钟");
        for (Category category: categories) {
            Type type = new Type();
            int count = (int) ordersList.stream().filter(p-> p.getCategoryId()==category.getId()).count();
            type.setCount(count);
            type.setType(category.getCategory());
            typeList.add(type);
        }
        timesRes.setTypeList(typeList);
        List<Orders> orders = ordersList.stream().filter(p->!p.getSumTime().equals("未处理")).collect(Collectors.toList());
        if(orders.size()>0){
            Optional<Orders> maxTime = orders.stream().max(Comparator.comparingLong(Orders::getDiff));
            Optional<Orders> minTime = orders.stream().min(Comparator.comparingLong(Orders::getDiff));
            timesRes.setMaxTime(maxTime.get().getSumTime());
            timesRes.setMinTime(minTime.get().getSumTime());
            OptionalDouble avgTime = orders.stream().mapToLong(Orders::getDiff).average();
            System.out.println(avgTime.toString()+avgTime);
            timesRes.setAvgTime(getAvg((long) avgTime.getAsDouble()));
        }


        return timesRes;

    }
public static String getAvg(Long avgTime){
    long nm = 1000 * 60;// 一分钟的毫秒数
    long min = avgTime / nm ;
    return min+"分钟";
}





    }
